using System.Threading;
using OracleInternal.Common;

namespace OracleInternal.ConnectionPool
{
	internal class ChunkUpEvent
	{
		private SyncDictionary<string, ManualResetEventSlim> m_events;

		public ChunkUpEvent()
		{
			m_events = new SyncDictionary<string, ManualResetEventSlim>();
		}

		public string GetId(string db, string instance, string chunk)
		{
			return ((db == null) ? db : db.ToLowerInvariant()) + "|" + ((instance == null) ? instance : instance.ToLowerInvariant()) + "|" + ((chunk == null) ? chunk : chunk.ToLowerInvariant());
		}

		public void CreateEvent(string db, string instance, string chunk)
		{
			string id = GetId(db, instance, chunk);
			if (m_events[id] != null)
			{
				return;
			}
			lock (this)
			{
				if (m_events[id] == null)
				{
					m_events[id] = new ManualResetEventSlim();
				}
			}
		}

		public ManualResetEventSlim GetEvent(string db, string instance, string chunk)
		{
			string id = GetId(db, instance, chunk);
			lock (this)
			{
				return m_events[id];
			}
		}

		public void SetAndRemoveEvent(string db, string instance, string chunk)
		{
			string id = GetId(db, instance, chunk);
			lock (this)
			{
				if (m_events[id] != null)
				{
					m_events[id].Set();
					m_events[id] = null;
				}
			}
		}
	}
}
